//
//  LBWRefreshControl.swift
//  weibo
//
//  Created by Limonwei on 15/12/11.
//  Copyright © 2015年 heima. All rights reserved.
//

//刷新视图部分 继承UIControl  

import UIKit

//当前控件的高度
private let RefreshControlH: CGFloat = 50

//刷新控件的三种不同状态
//枚举
enum LBWRefreshControlState: Int {
    //默认状态或者松开手就回到默认状态
    case Normal = 0
    //将要刷新的状态 下拉之后松开手就会进入刷新的一个状态
    case Pulling = 1
    //正在刷新状态
    case Refreshing = 2
    
}

class LBWRefreshControl: UIControl {
    
    //之前的状态,用于在设置成normal的时候,判断上一次是否刷新状态
    var oldLBWState: LBWRefreshControlState = .Normal
    
    //当前控件所处于的状态
    var LBWState:LBWRefreshControlState = .Normal{
        
        didSet{
            switch LBWState {
                
            case .Pulling:
                
                printLog("显示松开刷新,箭头调转方向")
                messageLabel.text = "释放刷新"
                //箭头选装 执行动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                
                printLog("显示加载中... 隐藏箭头,菊花旋转")
                messageLabel.text = "加载中..."
                
                arrowIcon.hidden = true
                
                //菊花开始动画
                indicator.startAnimating()
                
                //增加顶部的滑动距离
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    var contentInset = self.scrollView!.contentInset
                    
                    contentInset.top += RefreshControlH
                    
                    self.scrollView?.contentInset = contentInset
                })
                
                //发送一个指定操作
                
                sendActionsForControlEvents(.ValueChanged)
                
            case .Normal:
                printLog("显示箭头并重置,隐藏菊花转,文字为下拉刷新")
                
                messageLabel.text = "下拉刷新"
                
                arrowIcon.hidden = false
                
                indicator.stopAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                //从刷新状态切换到默认状态调用
                if oldLBWState == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= RefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                }
            }
            oldLBWState = LBWState
        }
        
    }
    
    //结束刷新
    func endRefreshing(){
        LBWState = .Normal
    }
    
    //记录一个scrollView 添加到父控件
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图UI
    private func setupUI(){
        //背景颜色
        backgroundColor = UIColor.greenColor()
        
        //设置frame
        var frame = self.frame
        frame.size = CGSizeMake(SCREENW, RefreshControlH)
        frame.origin.y = -RefreshControlH
        self.frame = frame
        
        //添加控件
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicator)
        
        //添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
        }
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    //当前控件将要加到某一个控件上的时候调用这个方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断到底能不能滚动
        if let scrollView = newSuperview as? UIScrollView {
            //利用KVO监听newSuperView的滚动contentOffset
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            
            self.scrollView = scrollView
            
            var frame = self.frame
            frame.size.width = scrollView.frame.width
            
            self.frame = frame
        }
    }
    
    //KVO监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = scrollView?.contentOffset.y
        
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        
        //拉动的临界值 当前控件是否完整显示的临界值
        let conditionValue = -contentInsetTop - RefreshControlH
        
        if scrollView!.dragging {
            
            if LBWState == .Normal && contentOffsetY < conditionValue {
                //进入松手就刷新的状态
                LBWState = .Pulling
            }else if LBWState == .Pulling && contentOffsetY >= conditionValue {
                
                //进入默认状态
                LBWState = .Normal
            }
        }else{
            //刷新状态
            if LBWState == .Pulling {
                
                LBWState = .Refreshing
            }
        }
    }
    
    
    //释放kvo
    deinit {
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    //懒加载控件
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //显示文字的Label
    private lazy var messageLabel: UILabel = {
       
        let label = UILabel(textColor: UIColor.orangeColor(), fontSize: 12)
        label.text = "下拉刷新"
        
        return label
        
    }()
    
    //加载菊花视图控件
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    //背景图片

}




















